from datetime import datetime
from typing import List

import db.db as db
import emailservice as email
import jsl.jslutil as jsl
from db.connectmysql import global_db_cache  # 引入全局连接缓存实例
from entity.cbdata import CbData


def filter_bond_data_and_send_amail(cb_data_list: List[CbData],formatted_date) -> None:
    """
    筛选可转债的纯债价值大于现在价格的,邮件通知
    """
    filter_bond_value = [f"可转债价格小于纯债价格:\n"]
    bond_value_list = []
    filter_ytm_rt = [f"可转债收益率大于8%:\n"]
    ytm_rt_list = []
    for cb_data in cb_data_list:
        if float(cb_data.bond_value) > float(cb_data.price):
            # if float(cb_data.bond_value) > float(90.0):
            content = f"转债id:{cb_data.bond_id},名称:{cb_data.bond_nm},现价:{cb_data.price},纯债价格:{cb_data.bond_value}\n"
            filter_bond_value.append(content)
            bond_value_list.append(cb_data)
        if float(cb_data.ytm_rt) > 8.0:
            content = f"转债id:{cb_data.bond_id},名称:{cb_data.bond_nm},现价:{cb_data.price},收益率:{cb_data.ytm_rt}\n"
            filter_ytm_rt.append(content)
            ytm_rt_list.append(cb_data)
    if len(filter_bond_value) > 1:
        # 邮件通知
        csv_name = "可转债价格小于纯债价格_" + formatted_date + ".csv"
        jsl.save_data_csv(bond_value_list, csv_name, None)
        email.send_mail_bond_value("\n".join(filter_bond_value), None)
    if len(filter_ytm_rt) > 1:
        # 邮件通知
        email.send_mail_ytm_rt("\n".join(filter_ytm_rt), None)

        csv_name = "可转债收益率大于8_" + formatted_date + ".csv"
        jsl.save_data_csv(ytm_rt_list, csv_name, None)


def init_filter_bond_data(cb_data_list: List[CbData]) -> List[CbData]:
    """
    初始过过滤转债
     1.剔除非可转债
    2.剔除退市转债
     3.剔除已经强制赎回转债
    4.剔除回售转债
    @param cb_data_list: 原始转债信息
    @return:
    """
    filtered_list = []
    for cb_data in cb_data_list:

        if cb_data.btype != 'C':  # 非可转债
            continue
        if cb_data.blocked != 0:  # 非可转债
            continue

        if "退债" in str(cb_data.bond_nm):
            continue
        if cb_data.list_dt is None:  # 未上市
            continue
        if cb_data.bond_id is None:  # 转债id空
            continue
        if cb_data.price is None:  # 转债价格空
            continue
        if cb_data.year_left is None:  # 剩余年限空 公告强赎回
            continue
        if "已公告要强赎" in str(cb_data.ref_yield_info):
            continue
        if cb_data.putting == 'Y':  # 回售中标记
            continue
        # 正常转债
        filtered_list.append(cb_data)
    return filtered_list


def calculate_bond_data(cb_data_list: List[CbData], conn, cursor) -> List[CbData]:
    """
    计算可转债价值
    1.计算纯债价值
    2.计算期权价值
    3.计算非贴现收益率
    @param cursor:
    @param conn:
    @param cb_data_list: 原始转债信息
    @return:
    """
    filtered_list = []
    #   计算纯债价值和期权价值
    for cb_data in cb_data_list:
        float_year_left = float(cb_data.year_left)
        dis_rate = jsl.get_discount_rate(conn, cursor, None)  # 贴现率
        expire_value, rate_dic = db.get_rate_dic_bond_id(conn, cursor, cb_data.bond_id)  # 票面利率

        cb_data.bond_value = jsl.get_bond_value_jsl(float_year_left, dis_rate, rate_dic, expire_value)  # 纯债价值
        cb_data.option_value = round(cb_data.price - cb_data.bond_value)  # 期权价值

        # todo  简化收益率
        # cb_data.expire_rt = get_expire_rt(driver, cb_data.bond_id, cb_data.price, float_year_left)

        filtered_list.append(cb_data)

    return filtered_list


def filter_bond_data(cb_data_list: List[CbData]) -> List[CbData]:
    """
    5.条件筛选可转债
    1.筛选现价<纯债价值 通知保存
    2.筛选收益率>5% 通知保存
    3.筛选 价格 <130,收益率 <30%,转债规模,30亿元
    @param cb_data_list: 原始转债信息
    @return:
    """

    filtered_list = []
    for cb_data in cb_data_list:
        if float(cb_data.year_left) < 0.5:  # 剩余年限 <0.5
            continue
        if float(cb_data.price) > 130:  #
            continue
        if float(cb_data.premium_rt) > 30:  #
            continue
        if float(cb_data.curr_iss_amt) > 30:  #
            continue
        # 正常转债
        filtered_list.append(cb_data)
    return filtered_list


if __name__ == "__main__":
    # 默认获取当天时间
    # 获取当前日期和时间
    today = datetime.today()
    # 格式化为 "YYYYMMDD" 形式（年4位 + 月2位 + 日2位）
    formatted_date = today.strftime("%Y%m%d")  # 20250901
    conn, cursor = global_db_cache.get_connection("main_db")
    with conn:
        with cursor:
            # 1.集思录接口获取可转债信息
            cb_data_list = jsl.get_cb_data_jsl()
            if cb_data_list is not None:
                # 2.初始筛选可转债信息
                cb_data_list = init_filter_bond_data(cb_data_list)
            print("初始筛选后转债剩余数量:", len(cb_data_list))
            # 3.计算剩余可转债信息
            cb_data_list = calculate_bond_data(cb_data_list, conn, cursor)

            # 4.保存成csv文件中文
            csv_name_cn = "可转债数据_" + formatted_date + "_中文.csv"
            csv_name_en = "jsl_bond_data_" + formatted_date + ".csv"
            jsl.save_data_csv(cb_data_list, csv_name_cn, csv_name_en)
            # 5.条件筛选可转债
            # 统计有没有可转债价格低于纯债价值的重仓
            # 统计可转债收益率大于>8%的
            filter_bond_data_and_send_amail(cb_data_list,formatted_date)
            cb_data_list = filter_bond_data(cb_data_list)
            print("最终筛选后可转债数量:", len(cb_data_list))
            last_csv_name = "(最后)可转债估值结果_" + formatted_date + ".csv"

            jsl.save_data_csv(cb_data_list, last_csv_name, None)
    print("执行完成!!!!!!!")

"""
集思录转债信息获取流程
1.集思录接口获取可转债信息
2.初始筛选可转债信息
    1.剔除非可转债
    2.剔除退市转债
    3.剔除已经强制赎回转债
    4.剔除回售转债
3.计算剩余可转债信息
    1.计算纯债价值
    2.计算期权价值
    3.计算非贴现收益率
4.保存成csv文件中文
5.条件筛选可转债
    1.筛选现价<纯债价值 通知保存
    2.筛选收益率>5% 通知保存
    3.筛选 价格 <130,收益率 <30%,转债规模,30亿元
"""
